#!/bin/bash
#
# Downloads data of a specific entity kind from the datastore into a file.
#

USAGE="Usage: gae_download local|remote kind"

if [ $# -lt 2 ]; then
  echo $USAGE
  exit 1
fi

if [ ${0:0:1} = "/" ]; then
  DIR=`dirname $0`
else
  DIR=`pwd`/`dirname $0`
fi 

echo "Work directory: " $DIR
cd $DIR

# Local dev or remote server
if [ $1 = "local" ]; then
  URL="http://localhost:8888/admin/remote_api"
elif [ $1 = "remote" ]; then
  URL="http://virtual-hockey.appspot.com/admin/remote_api"
else
  echo "The first argument must be either 'local' or 'remote'!"
  echo $USAGE
  exit 2
fi 

# Check that $2.csv exists
FILE="../testdata/csv/${2}.csv"
if [ -f $FILE ]; then
  echo "File $FILE already exists. Please rename or delete it prior to downloading new data."
  exit 3
else
  echo "New $FILE will be created."
fi 

# Check that bulkloader.yaml exists
CFGFILE="../testdata/bulkloader.yaml"
if [ -f $CFGFILE ]; then
  echo "Invoking GAE Python bulk uploader to download $FILE using config in $CFGFILE ..."
else
  echo "Config file $CFGFILE does not exist. No data will be uploaded."
  exit 3
fi

appcfg.py download_data --application=virtual-hockey --config_file=$CFGFILE --filename=$FILE --kind=$2 --url $URL

# Move all bulkloader-* log files to ../../../target/
if [ -d "../../../target" ]; then
  echo "target directory already exists."
else
  echo "Creating target directory."
  mkdir ../../../target
fi

echo "Copying log files to ../../../target"
mv bulkloader-* ../../../target

